'''
https://leetcode.cn/problems/find-leaves-of-binary-tree
'''
from typing import Optional, List


# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution:
    def findLeaves(self, root: Optional[TreeNode]) -> List[List[int]]:
        res = []
        def f(root):
            if not root:
                return -1
            height = max(f(root.left), f(root.right)) + 1
            if len(res) == height:
                res.append([])
            res[height].append(root.val)
            return height
        f(root)
        return res
